package com.blog.blog.service;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LikeService {

    private final RedissonClient redissonClient;

    public LikeService(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    private String keyForComment(Long commentId) {
        return "comment:like:count:" + commentId;
    }

    private String keyForActor(Long commentId, String actorKey) {
        return "comment:like:actor:" + commentId + ":" + actorKey;
    }

    public long incrementCommentLike(Long commentId) {
        RAtomicLong counter = redissonClient.getAtomicLong(keyForComment(commentId));
        return counter.incrementAndGet();
    }

    public Map<Long, Long> getCommentLikes(List<Long> ids) {
        Map<Long, Long> res = new HashMap<>();
        if (ids == null || ids.isEmpty()) return res;
        for (Long id : ids) {
            RAtomicLong counter = redissonClient.getAtomicLong(keyForComment(id));
            res.put(id, counter.get());
        }
        return res;
    }

    /**
     * 按评论+参与者唯一键去重注册一次点赞，成功返回 true；已点过返回 false。
     */
    public boolean registerCommentLike(Long commentId, String actorKey, long ttlSeconds) {
        String k = keyForActor(commentId, actorKey);
        RBucket<String> bucket = redissonClient.getBucket(k);
        boolean ok = bucket.trySet("1", ttlSeconds, TimeUnit.SECONDS);
        return ok;
    }

    public long getCommentLikeCount(Long commentId) {
        RAtomicLong counter = redissonClient.getAtomicLong(keyForComment(commentId));
        return counter.get();
    }
}


